const http = require('http');
const fs = require('fs');
const path = require('path');
const url = require('url');

const server = http.createServer((req, res) => {
    const parsedUrl = url.parse(req.url, true);
    
    // 如果是API请求，代理到后端
    if (req.url.startsWith('/springboot1i659')) {
        // Docker 容器内使用服务名，本地开发使用 localhost
        const backendHost = process.env.BACKEND_HOST || 'localhost';
        const backendPort = process.env.BACKEND_PORT || 8080;
        
        const options = {
            hostname: backendHost,
            port: backendPort,
            path: req.url,
            method: req.method,
            headers: {
                ...req.headers,
                'host': `${backendHost}:${backendPort}`
            }
        };

        const proxyReq = http.request(options, (proxyRes) => {
            // 设置CORS头
            res.setHeader('Access-Control-Allow-Origin', '*');
            res.setHeader('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
            res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With, Token');
            
            res.writeHead(proxyRes.statusCode, proxyRes.headers);
            proxyRes.pipe(res);
        });

        proxyReq.on('error', (err) => {
            console.error('代理请求失败:', err.message);
            res.writeHead(500);
            res.end('后端服务连接失败，请确保后端服务已启动在8080端口');
        });

        if (req.method !== 'GET' && req.method !== 'HEAD') {
            req.pipe(proxyReq);
        } else {
            proxyReq.end();
        }
        return;
    }

    // 处理静态文件
    let filePath = parsedUrl.pathname === '/' ? '/index.html' : parsedUrl.pathname;
    filePath = path.join(__dirname, 'dist', filePath);

    fs.readFile(filePath, (err, data) => {
        if (err) {
            res.writeHead(404);
            res.end('404 Not Found');
            return;
        }

        const ext = path.extname(filePath);
        const mimeTypes = {
            '.html': 'text/html',
            '.js': 'text/javascript',
            '.css': 'text/css',
            '.png': 'image/png',
            '.jpg': 'image/jpeg',
            '.gif': 'image/gif',
            '.svg': 'image/svg+xml',
            '.json': 'application/json',
            '.woff': 'font/woff',
            '.woff2': 'font/woff2',
            '.ttf': 'font/ttf',
            '.ico': 'image/x-icon'
        };

        res.writeHead(200, { 'Content-Type': mimeTypes[ext] || 'text/plain' });
        res.end(data);
    });
});

server.listen(8088, () => {
    const backendHost = process.env.BACKEND_HOST || 'localhost';
    const backendPort = process.env.BACKEND_PORT || 8080;
    console.log('管理端启动成功: http://localhost:8088');
    console.log(`API代理到后端: http://${backendHost}:${backendPort}/springboot1i659`);
    console.log('请确保后端服务已在8080端口启动');
});